import dataArray from "@/utils/data";

export function paging(page = {}) {
    const returnData = {
        rows: [],
        pageNum: getTotalPages(dataArray, page.pageSize),
    }
    returnData.rows = filterPageRows(page)

    return returnData

}

/**
 * 找到对应数据
 * @param page
 * @returns {*[]}
 */
function filterPageRows(page) {
    // if (Object.keys(page).length === 0) return dataArray

    const startIndex = (page.pageNo - 1) * page.pageSize;
    const endIndex = startIndex + page.pageSize;
    return dataArray.slice(startIndex, endIndex);
}

/**
 * 计算数组的总页数
 * @param {Array} array - 需要分页的数组
 * @param {number} itemsPerPage - 每页的项数
 * @returns {number} - 总页数
 */
function getTotalPages(array, itemsPerPage) {
    if (!Array.isArray(array)) {
        throw new Error("第一个参数必须是数组");
    }
    if (typeof itemsPerPage !== "number" || itemsPerPage <= 0) {
        throw new Error("第二个参数必须是大于0的数字");
    }

    return Math.ceil(array.length / itemsPerPage);
}


export function dragWindowBorder() {
    const resizer = document.getElementById('resizer');
    const left_tree_box = document.getElementById('left_tree_box');
    const right_substance_box = document.getElementById('right_substance_box');
    let startX, startWidth1, startWidth2;

    const initDrag = e => {
        startX = e.clientX;
        startWidth1 = left_tree_box.offsetWidth;
        startWidth2 = right_substance_box.offsetWidth;
        document.documentElement.addEventListener('mousemove', doDrag, false);
        document.documentElement.addEventListener('mouseup', stopDrag, false);
    };

    const doDrag = e => {
        const delta = e.clientX - startX;
        left_tree_box.style.width = (startWidth1 + delta) > 200 ? (startWidth1 + delta) + 'px' : '200px'
        right_substance_box.style.width = (startWidth2 - delta) > 1100 ? (startWidth2 - delta) + 'px' : '1100px'
    };
    const stopDrag = () => {
        document.documentElement.removeEventListener('mousemove', doDrag, false);
        document.documentElement.removeEventListener('mouseup', stopDrag, false);
    };

    resizer.addEventListener('mousedown', initDrag, false);
}


